package cn.south.campus.admin.interceptor;

import cn.south.campus.admin.config.TokenConfig;
import cn.south.campus.admin.sys.model.bo.LoginContext;
import cn.south.campus.admin.sys.model.bo.LoginInfo;
import cn.south.campus.common.cache.CacheService;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *
 * </p>
 *
 * @author chow
 * @since 2023/3/14 17:16
 */
@Component
@AllArgsConstructor
@SuppressWarnings("all")
public class RefreshLoginInterceptor implements HandlerInterceptor {

    private final CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的token
        String token = request.getHeader(TokenConfig.HEADER);
        if (!StringUtils.hasLength(token)) {
            return true;
        }
        //基于TOKEN获取redis中的用户
        Object cacheObject = cacheService.getCacheObject(token);
        //判断用户是否存在
        if (cacheObject == null) {
            return true;
        }
        LoginInfo loginInfo = JSON.parseObject(cacheObject.toString(), LoginInfo.class);

        //存在，保存用户信息到ThreadLocal
        LoginContext.setContext(loginInfo);

        //刷新token的有效期
        cacheService.expire(token, TokenConfig.EXPIRE);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        LoginContext.remove();
    }
}
